# encoding:utf8
''' 2017-7-25 pylint + fixbug '''

import os
import json
import shutil
import hashlib
import logging
from pylibs.lpkg import luajit_pack
from pylibs.verpack import chk_resinfo
from pylibs.verpack import VersionSvnDiff
from pylibs.sqlite import SqliteMgr

from pylibs.texture import pack_platicon
from pylibs.texture import pack_platpage
from pylibs.texture import pack_platgamepage


class LuaDev(object):
    ''' 开发使用的脚本 '''
    @staticmethod
    def todo():
        '''
        todo
        '''
        pass


class LuaPackRes(object):
    ''' 打包资源的脚本 '''
    @staticmethod
    def chk_resmd5(frompath, basepath, ignorefunc):
        '''  
        查看资源文件路径的md5值
        '''
        ret = dict()
        if frompath.split(os.sep)[-1] is "res":
            logging.error("Packres dir must start with <res>!")
            return

        def _getmd5(fileobj):
            m5 = hashlib.md5()
            data = file(fileobj, "rb")
            while True:
                tdata = data.read(1024)
                if not tdata:
                    break
                m5.update(tdata)
            data.close()
            return m5.hexdigest()
        
        def _iter_res(tarpath):
            for filename in os.listdir(tarpath):
                fileobj = os.path.join(tarpath, filename)
                if os.path.isfile(fileobj):
                    if ignorefunc(fileobj) == False:
                        ret[fileobj.replace(basepath, "")] = _getmd5(fileobj)
                    else:
                        logging.info("The file is ignore by the rule!--->>%s", fileobj)
                else:
                    _iter_res(fileobj)
                
        _iter_res(frompath)
        return ret


    @staticmethod 
    def sql_create_tb(dbfile, tbname, tbconf):
        ''' 创建表 '''
        SqliteMgr.inc(dbfile).create_table(tbname, tbconf)
    
    @staticmethod 

    def sql_save_res(dbfile, tbname, rescont):
        ''' 保存一条文件 '''
        SqliteMgr.inc(dbfile).insert_data(tbname, rescont)

    @staticmethod
    def sql_update_res(dbfile, tbname, dbdata, condition):
        ''' 更新某个key '''
        SqliteMgr.inc(dbfile).update_data(tbname, dbdata, condition)

    @staticmethod 
    def sql_save_reslist(dbfile, tbname, reslist):
        ''' 保存文件列表 '''
        datalist = []
        for name, md5val in reslist.items():
            val = dict(str1=name, str2=md5val)
            datalist.append(val)
        SqliteMgr.inc(dbfile).insert_datalist(tbname, datalist)

    @staticmethod
    def sql_get_data(dbfile, tbname, condition):
        ''' 获取数据 '''
        return SqliteMgr.inc(dbfile).get_data(tbname, condition)

    @staticmethod
    def sql_update_reslist(dbfile, reslist):
        ''' 更新文件列表 '''
        pass


class LuaPackbin(object):
    ''' 打包使用的脚本 '''
    @staticmethod
    def lua_lpack(frompath, tarpath, packtype="jitc"):
        '''
        打包脚本
            @frompath  源脚本目录
            @tarpath   目标目录
            @packtype pack类型, "jitc", "luac", "onlyzip"
        '''
        return luajit_pack(frompath, tarpath, packtype)


class LuaPackHot(object):
    ''' 热更新打包使用的脚本 '''
    @staticmethod
    def svn_difflist(hotpackconf, platform="android"):
        '''
        生成热更新资源
            @respath 源资源路径
            @snum 开始的版本号
            @enum 结束的版本号
            @verpath 目标资源路径
        '''
        packer = VersionSvnDiff(hotpackconf, platform)
        packer.chk_dif()
        packer.copy_diffres()

        datapath = os.path.join(hotpackconf["verpath"], hotpackconf["verinfo"])
        datafile = os.path.join(datapath, hotpackconf["verinfo"] + ".data")
        LuaPackHot.crt_verinfo_list(os.path.join(
            datapath, "res"), datafile, "json")
        shutil.make_archive(hotpackconf["verinfo"], "zip", datapath)

    @staticmethod
    def crt_verinfo_list(respath, tarfile, datatype="json"):
        '''
        生成热更新数据文件
            @respath     源资源路径
            @tarfile     生成的数据文件路径
            @datatype    生成的数据文件类型
        '''
        infolist = chk_resinfo(respath, datatype)
        if os.path.isfile(tarfile):
            os.remove(tarfile)
        datafile = file(tarfile, "wb")

        if datatype == "txt":
            for info in infolist:
                exstr = "" if (infolist.index(info) ==
                               len(infolist) - 1) else ","
                datafile.write(info + exstr)
        elif datatype == "json":
            datafile.write(json.dumps(infolist, sort_keys=True, indent=4))
        datafile.close()

    @staticmethod
    def pack_icon(basetexture, tardir, platform):
        '''  
        打包文件图标
            @basetexture 原始纹理路径
            @tardir      目标文件夹
            @platform    图标平台
        '''
        pack_platicon(basetexture, tardir, platform)

    @staticmethod
    def pack_page(basetexture, tardir, platform):
        '''  
        打包文件首页
            @basetexture 原始纹理路径
            @tardir      目标文件夹
            @platform    图标平台
        '''
        pack_platpage(basetexture, tardir, platform)

    @staticmethod
    def pack_game_pack(basetexture, tartexture, platform):
        '''  
        打包文件首页
            @basetexture 原始纹理路径
            @tardir      目标文件夹
            @platform    图标平台
        '''
        pack_platgamepage(basetexture, tartexture, platform)


if __name__ == "__main__":
    pass
